package com.landinfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.landinfo.domain.PageResult;
import com.landinfo.domain.PhotoType;
import com.landinfo.domain.PhotoTypePath;
import com.landinfo.repository.PhotoTypePathRepository;
import com.landinfo.repository.PhotoTypeRepository;
import com.landinfo.service.PhotoTypeService;
import org.apache.commons.collections.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Transactional
public class PhotoTypeServiceImpl implements PhotoTypeService {

    @PersistenceContext
    private EntityManager entityManager;

    private final PhotoTypeRepository photoTypeRepository;

    @Autowired
    private PhotoTypePathRepository photoTypePathRepository;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");


    public PhotoTypeServiceImpl(PhotoTypeRepository photoTypeRepository) {
        this.photoTypeRepository = photoTypeRepository;
    }


    @Override
    public PhotoType save(PhotoType photoType) {
        return this.photoTypeRepository.save(photoType);
    }

    @Override
    public List<PhotoType> findAll() {
        Iterator<PhotoType> list = this.photoTypeRepository.findAll().iterator();
        if (list != null) {
            return IteratorUtils.toList(list);
        } else {
            return null;
        }
    }

    @Override
    public List<PhotoType> queryByName(String name) {
        return null;
    }

    @Override
    public PhotoType findOne(String id) {
        return this.photoTypeRepository.findById(id).get();
    }

    @Override
    public void delete(String id) {
        this.photoTypeRepository.deleteById(id);
    }

    @Override
    public List<String> getAllTab() {
        String hql = String.format("select speciesName from PhotoType where speciesName <> null and speciesName <> ''  group by speciesName order by speciesName");
        Query query = entityManager.createQuery(hql);
        List<String> resultList = query.getResultList();
        return resultList;
    }

    @Override
    public String findByTagsAndCreateDateTime(String tags, String camerasStr, Date startDateTime, Date endDateTime, String orderBy, Pageable pageable) {
        String hql = "from PhotoType a  where (select count(o) from a.photoTypePaths o)>0";
        String countHql = "select count(*) from PhotoType a where (select count(o) from a.photoTypePaths o)>0";
//        String hql="";
//        String countHql="";
        if (tags != null && !"".equals(tags.trim())) {
            hql += String.format(" and a.speciesName in (%s)", tags);
            countHql += String.format(" and a.speciesName in (%s)", tags);
        }
        if(camerasStr != null && !"all".equals(camerasStr.trim())){
            hql += String.format(" and a.layoutPointNo in (%s)", camerasStr);
            countHql += String.format(" and a.layoutPointNo in (%s)", camerasStr);
        }
        if (startDateTime != null) {
            hql += String.format(" and a.createDateTime>='%s'", sdf2.format(startDateTime));
            countHql += String.format(" and a.createDateTime>='%s'", sdf2.format(startDateTime));
        }
        if (endDateTime != null) {
            hql += String.format(" and a.createDateTime<='%s'", sdf2.format(endDateTime));
            countHql += String.format(" and a.createDateTime<='%s'", sdf2.format(endDateTime));
        }
        hql += String.format(" order by %s desc", orderBy);
//        hql += " order by a.createDateTime desc";
//        countHql += " order by createDateTime desc";

//        PageResult pageResult = new PageResult();
        HashMap<String,Object> hashMaps=new HashMap<>();
        Query query = entityManager.createQuery(hql);
        Query queryCount = entityManager.createQuery(countHql);
//        pageResult.setRecordCount(Integer.parseInt(queryCount.getSingleResult().toString()));
        hashMaps.put("recordCount", Integer.parseInt(queryCount.getSingleResult().toString()));

        Integer number = pageable.getPageNumber() - 1;
        Integer size = pageable.getPageSize();
        query.setFirstResult(number * size);
        query.setMaxResults(size);
//        pageResult.setDatas(query.getResultList());
        hashMaps.put("result", query.getResultList());
        entityManager.clear();
//        for (int i = 0; i < pageResult.getDatas().size(); i++) {
//            PhotoType photoType=(PhotoType) pageResult.getDatas().get(i);
//            if(photoType.getPhotoTypePaths().size()>1){
//               Integer x= photoType.getPhotoTypePaths().size();
//               break;
//            }
//        }
        String res = JSON.toJSONStringWithDateFormat(hashMaps, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);

        return res;
    }

    @Override
    public Iterable<PhotoTypePath> getAllPhotoTypePath() {
        return photoTypePathRepository.findAll();
    }

    @Override
    public List<String> groupByCreateDateTime() {
        String hql = String.format("select createDateTime from PhotoType group by createDateTime");
        Query query = entityManager.createQuery(hql);
        return query.getResultList();
    }

    @Override
    public Boolean updateCreateDateTime() {
        String hql = String.format("from PhotoType");
//        Query query = entityManager.createQuery(hql);
//        List<PhotoType> photoTypes = query.getResultList();
        try {
            Iterable<PhotoType> photoTypes = photoTypeRepository.findAll();
            for (PhotoType photoType : photoTypes) {
                try {
                    photoType.setCreateDateTime(sdf2.parse(photoType.getShootDate().replace("/", "-") + " " + photoType.getShootTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            this.photoTypeRepository.saveAll(photoTypes);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }


//    @Override
//    public Page<PhotoType> findByPhotoLabelAndCreateDateTime(String photoLable, Date startDateTime, Date endDateTime, Pageable pageable) {
////        return this.photoTypeRepository.findByPhotoLabel(photoLable,  pageable);
//        //return this.photoTypeRepository.findByPhotoLabelAndCreateDateTimeBetween(photoLable, startDateTime, endDateTime, pageable);
//        String sql = String.format("from PhotoType where photoLable='%s' ", photoLable );
//        Query query = entityManager.createNativeQuery(sql);
//        return  null;
//    }
//
//    @Override
//    public List<PhotoType> findByPhotoLabelAndCreateDateTime2(String photoLable, Date startDateTime, Date endDateTime) {
//        String[] photoLables = photoLable.split(",");
//        //return this.photoTypeRepository.findByPhotoLabelAndCreateDateTimeBetween(photoLable, startDateTime, endDateTime, pageable);
//        String sql = String.format("from PhotoType where createDateTime > '%tF' and createDateTime < '%tF' and ", startDateTime, endDateTime);
//        for (int i = 0; i< photoLables.length; i++){
//            if(i == 0){
//                sql += String.format(" photoLabel like '%%%s%%'", photoLables[i]);
//            }else {
//                sql += String.format(" or photoLabel like '%%%s%%'", photoLables[i]);
//            }
//        }
//        sql += String.format(" ORDER BY createDateTime DESC");
//        Query query = entityManager.createQuery(sql);
//        List list = query.getResultList();
//        return  list;
//    }
}
